<template>
  <div id="app" class="container-fluid">
    <div id="toolbar">
      <button type="button" class="btn btn-primary" @click="add(1)">
        New Server
      </button>
      <button type="button" class="btn btn-primary" @click="add(0)">
        New Client
      </button>
    </div>
    <tabs>
      <tab class="list-group" header="Summary" :pined="true">
        <h1 class="text-center" v-if="!msgs.length">
          <button type="button" class="btn btn-primary btn-lg" @click="add(1)">
            New Server
          </button>
          <button type="button" class="btn btn-primary btn-lg" @click="add(0)">
            New Client
          </button>
        </h1>
        <msg :msgs="msgs"></msg>
      </tab>
      <tab v-for="t in tabs" :header="t.name">
        <server :mqtt="mqtt" :name.sync="t.name" v-if="t.type"></server>
        <client :mqtt="mqtt" :name.sync="t.name" v-else></client>
      </tab>
    </tabs>
  </div>
</template>

<script>
const Utils = require('./utils');
const extend = Utils.extend;

const Tabs = require('./components/tabs');
const Tab = require('./components/tab');
const Server = require('./components/server');
const Client = require('./components/client');
const Msg = require('./components/msg');

const mqttClient = mqtt.connect(`ws://${window.location.hostname}:9033`);

exports.components = {
  Tabs,
  Tab,
  Server,
  Client,
  Msg
};

exports.data = () => {
  return {
    mqtt: mqttClient,
    tabs: [],
    msgs: []
  };
};

exports.methods = {
  add(type) {
    this.tabs.push({
      type
    });
  },
  onMessage(topic, payload) {
    try {
      topic = JSON.parse(topic);
    } catch (e) { e; }
    const msg = extend({
      msg: payload.toString(),
      t: new Date().toLocaleTimeString()
    }, topic);
    const _this = this;
    _this.msgs.unshift(msg);
    if (msg.type) {
      _this.$broadcast(msg.type, msg);
    }
  },
  onError(err) {
    this.msgs.unshift({ err });
  }
};

exports.ready = function() {
  const _this = this;

  Utils.$global = _this;

  mqttClient.on('message', _this.onMessage);
  mqttClient.on('error', _this.onError);
};
</script>

<style lang="stylus">
@import "styles/index"

#app
  padding-top: $padding-large-vertical

#toolbar
  float: right
</style>
